package com.cn.longdistancebusstation.registerAndLogin;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.cn.longdistancebusstation.R;
import com.cn.longdistancebusstation.annotation.LoginStatus;
import com.cn.longdistancebusstation.base.BaseActivity;
import com.cn.longdistancebusstation.global.GlobalVariable;
import com.cn.longdistancebusstation.httpHelper.HttpHelper;
import com.cn.longdistancebusstation.httpapi.HttpService;
import com.cn.longdistancebusstation.model.Coupons;
import com.cn.longdistancebusstation.model.Integration;
import com.cn.longdistancebusstation.model.Result;
import com.cn.longdistancebusstation.model.UserInfo;
import com.google.gson.Gson;

import java.math.BigDecimal;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.http.HTTP;

/**
 * Created by Administrator on 2018/1/17.
 */

public class LoginActivity extends BaseActivity implements View.OnClickListener {
    private EditText mUserNameEditText, mPasswordEditText;
    private Button btn_login;
    private TextView mRegisterTextView, mForgetPwdTextView, mCancleTextView;
    private SharedPreferences sharedPreferences;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getSupportActionBar().hide();
        setContentView(R.layout.activity_login);
        initView();
        registerBroadcast();
    }

    private void initView() {
        mUserNameEditText = (EditText) findViewById(R.id.login_username);
        mUserNameEditText.setOnClickListener(this);
        mPasswordEditText = (EditText) findViewById(R.id.login_pwd);
        mPasswordEditText.setOnClickListener(this);
        btn_login = (Button) findViewById(R.id.btn_login);
        btn_login.setOnClickListener(this);
        mRegisterTextView = (TextView) findViewById(R.id.tv_register);
        mRegisterTextView.setOnClickListener(this);
        mForgetPwdTextView = (TextView) findViewById(R.id.tv_forget_pwd);
        mForgetPwdTextView.setOnClickListener(this);
        mCancleTextView = (TextView) findViewById(R.id.cancle);
        mCancleTextView.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_login:
                String username = mUserNameEditText.getText().toString();
                String pwd = mPasswordEditText.getText().toString();
                if (username.equals(" ") && pwd.equals(" ")) {
                    Toast.makeText(this, "用户名或密码为空", Toast.LENGTH_SHORT).show();
                    btn_login.setClickable(false);
                } else {
                    check();
                }
                break;
            case R.id.tv_register:
                signUp();
                break;
            case R.id.tv_forget_pwd:
                forgetPwd();
                break;
            case R.id.cancle:
                finish();
                break;
        }

    }

    private void signUp() {
        Intent in = new Intent(this, RegisterActivity.class);
        startActivity(in);
    }

    private void check() {
        String telephone = mUserNameEditText.getText().toString();
        Retrofit retrofit = new HttpHelper.HttpServiceBuilder().build().getRetrofit();
        HttpService httpService = retrofit.create(HttpService.class);
        Call<Result> call = httpService.checkPhoneIsExist(telephone);
        call.enqueue(new Callback<Result>() {
            @Override
            public void onResponse(Call<Result> call, Response<Result> response) {
                Gson gson = new Gson();
                Result result = response.body();
                Boolean isSuccess = result.getHead().getSuccess();
                if (isSuccess) {
                    Toast.makeText(LoginActivity.this, "该手机号还未注册", Toast.LENGTH_SHORT).show();
//                    btn_login.setClickable(false);
                } else {
                    login();

                }
            }


            @Override
            public void onFailure(Call<Result> call, Throwable t) {

            }
        });
    }

    private void login() {
        SharedPreferences sharedPreferences=getSharedPreferences("data",MODE_PRIVATE);
        final String uName=sharedPreferences.getString("new_telephone_number","");
        final String username = mUserNameEditText.getText().toString().trim();
        final String pwd = mPasswordEditText.getText().toString().trim();
        showHud();
        Retrofit retrofit = new HttpHelper.HttpServiceBuilder().build().getRetrofit();
        HttpService httpService = retrofit.create(HttpService.class);
        Call<Result<UserInfo>> call = httpService.login(username, pwd);
        call.enqueue(new Callback<Result<UserInfo>>() {
            @Override
            public void onResponse(Call<Result<UserInfo>> call, Response<Result<UserInfo>> response) {
                hideHud();
                Gson gson = new Gson();
                Result result = response.body();
                Log.d("登录用户信息",result+"");
                Boolean isSuccess = result.getHead().getSuccess();
                UserInfo userInfo = (UserInfo) result.getBody();

                if (isSuccess) {
                    String id = userInfo.getId();
                    Log.d("用户id",id);
                    String integral=userInfo.getIntegral();
                    Log.d("积分",integral);
                    String ticketNumbers=userInfo.getTicketNum();
                    String couponLimit=userInfo.getCoupon();
                    SharedPreferences.Editor editor = getSharedPreferences("data", MODE_PRIVATE).edit();
                    editor.putString("telephone", username);
                    editor.putString("password", pwd);
                    editor.putString("ticketNums",ticketNumbers);
                    editor.putString("couponLimit",couponLimit);

                    editor.commit();
                    //
                    GlobalVariable.setUserID(id);
                    GlobalVariable.setLoginStatus(LoginStatus.STATUS_LOGIN);
                    GlobalVariable.setTicketNumForCondition(Integer.parseInt(ticketNumbers));
                    GlobalVariable.setDiscountValueForCondition(new BigDecimal(couponLimit));
                    finish();
                } else {
                    GlobalVariable.setLoginStatus(LoginStatus.STATUS_LOGOUT);
                    Toast.makeText(LoginActivity.this, result.getHead().getMsg(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<Result<UserInfo>> call, Throwable t) {
                hideHud();
                Toast.makeText(LoginActivity.this, t.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
    private void forgetPwd() {
        Intent in = new Intent(LoginActivity.this, VerifyActivity.class);
        startActivity(in);

    }
    MyReceiver receiver;
    private void registerBroadcast() {
        // 注册广播接收者
        receiver = new MyReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("exit_current_boundary");
        this.registerReceiver(receiver,filter);
    }
    class MyReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals("exit_current_boundary")){
                finish();
            }
        }
    }


}
